<!--
 * @Description: 回退重做
-->

<template>
  <div class="tool-box">
    <div :data-name="`撤销(${list.length})`" :class="['tool-item', !list.length ? 'disabled' : '']" @click="undo">
      <svg t="1683133391854" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
        p-id="17729" width="26" height="26">
        <path
          d="M761.856 1024c113.728-206.048 132.896-520.32-313.856-509.824l0 253.824-384-384 384-384 0 248.384c534.976-13.952 594.56 472.224 313.856 775.616z"
          fill="#444444" p-id="17730"></path>
      </svg>
    </div>
    <div :data-name="`重做(${redoList.length})`" :class="['tool-item', !redoList.length ? 'disabled' : '']" @click="redo">
      <svg t="1683133357549" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
        p-id="15915" width="26" height="26">
        <path
          d="M576 248.384l0-248.384 384 384-384 384 0-253.824c-446.752-10.496-427.584 303.776-313.856 509.824-280.704-303.424-221.088-789.568 313.856-775.616z"
          fill="#444444" p-id="15916"></path>
      </svg>
    </div>
  </div>
</template>

<script>
import select from '../mixins/select';
import { keyNames, hotkeys } from '../core/initHotKeys';

const maxStep = 10;

export default {
  name: 'ToolBar',
  mixins: [select],
  data() {
    return {
      index: 0,
      redoList: [],
      list: [],
      time: '',
    };
  },
  created() {
    // 有更新时记录进度
    this.canvas.c.on({
      'object:modified': this.save,
      // 'object:rotating': this.save,
      // 'object:scaling': this.save,
      // 'object:moving': this.save,
      // 'object:skewing': this.save,
      'selection:updated': this.save,
    });

    hotkeys(keyNames.ctrlz, this.undo);
  },

  methods: {
    // 保存记录
    save(event) {
      // 过滤选择元素事件
      const isSelect = event.action === undefined && event.e;
      if (isSelect) return;
      const data = this.canvas.editor.getJson();
      if (this.list.length > maxStep) {
        this.list.shift();
      }
      this.list.push(data);
    },
    // 后退
    undo() {
      if (this.list.length) {
        const item = this.list.pop();
        this.redoList.push(item);
        this.renderCanvas(item);
      }
    },
    // 重做
    redo() {
      if (this.redoList.length) {
        const item = this.redoList.pop();
        this.list.push(item);
        this.renderCanvas(item);
      }
    },
    // 根据数据渲染
    renderCanvas(data) {
      this.canvas.c.clear();
      this.canvas.c.loadFromJSON(data, this.canvas.c.renderAll.bind(this.canvas.c));
      this.canvas.c.requestRenderAll();
    },
  },
};
</script>

<style scoped lang="scss">
</style>
